package com.mewp.permissions.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mewp.permissions.common.entity.ResultCodeEnum;
import com.mewp.permissions.common.utils.MenuHelper;
import com.mewp.permissions.common.utils.RouterHelper;
import com.mewp.permissions.model.po.SysMenu;
import com.mewp.permissions.model.po.SysRoleMenu;
import com.mewp.permissions.model.vo.AssginMenuVo;
import com.mewp.permissions.model.vo.RouterVO;
import com.mewp.permissions.system.execption.CustomerException;
import com.mewp.permissions.system.mapper.SysMenuMapper;
import com.mewp.permissions.system.mapper.SysRoleMapper;
import com.mewp.permissions.system.mapper.SysRoleMenuMapper;
import com.mewp.permissions.system.service.SysMenuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author mewp
 * @description 针对表【sys_menu(菜单表)】的数据库操作Service实现
 * @createDate 2023-07-28 12:12:56
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {
    @Resource
    private SysMenuMapper menuMapper;
    @Resource
    private SysRoleMapper roleMapper;
    @Resource
    private SysRoleMenuMapper roleMenuMapper;

    @Override
    public List<SysMenu> findNodes() {
        //全部权限列表
        List<SysMenu> menuList = this.list();
        if (CollectionUtils.isEmpty(menuList)) {
            return Collections.emptyList();
        }
        //构建树形结构
        return MenuHelper.buildMenu(menuList);
    }

    @Override
    public boolean removeById(Serializable id) {
        LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getParentId, id);
        int count = this.count(queryWrapper);
        if (count > 0) {
            throw new CustomerException(ResultCodeEnum.NODE_ERROR);
        }
        return menuMapper.deleteById(id) > 0;
    }

    @Override
    public List<SysMenu> findMenuByRoleId(Long roleId) {
        //获取所有status为1的权限列表
        LambdaQueryWrapper<SysMenu> menuQueryWrapper = new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getStatus, 1);
        List<SysMenu> menuList = menuMapper.selectList(menuQueryWrapper);
        //根据角色id获取角色权限
        LambdaQueryWrapper<SysRoleMenu> roleMenuQueryWrapper = new LambdaQueryWrapper<SysRoleMenu>()
                .eq(SysRoleMenu::getRoleId, roleId);
        List<SysRoleMenu> roleMenus = roleMenuMapper.selectList(roleMenuQueryWrapper);

        //获取该角色已分配的所有权限id
        List<Long> roleMenuIds = new ArrayList<>();
        for (SysRoleMenu roleMenu : roleMenus) {
            roleMenuIds.add(roleMenu.getMenuId());
        }
        //遍历所有权限列表
        for (SysMenu sysMenu : menuList) {
            //设置权限分配情况
            sysMenu.setIsSelect(roleMenuIds.contains(sysMenu.getId()));
        }

        //将权限列表转换成权限树形结构
        return MenuHelper.buildMenu(menuList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean doAssign(AssginMenuVo assetsMenuVo) {
        Long roleId = assetsMenuVo.getRoleId();
        //删除已分配的权限
        LambdaQueryWrapper<SysRoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleMenu::getRoleId, roleId);
        roleMenuMapper.delete(queryWrapper);

        //遍历所有已选择的权限id
        List<SysRoleMenu> list = new ArrayList<>();
        for (Long menuId : assetsMenuVo.getMenuIdList()) {
            SysRoleMenu roleMenu = new SysRoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuId);
            list.add(roleMenu);
        }

        //批量插入权限
        return roleMenuMapper.insert(list);
    }

    @Override
    public List<RouterVO> getUserMenuList(Long userId) {
        List<SysMenu> menuList = getMenuListByUserId(userId);
        //构建树形数据
        List<SysMenu> menus = MenuHelper.buildMenu(menuList);
        //构建路由
        return RouterHelper.buildRouters(menus);
    }

    @Override
    public List<String> getUserButtonList(Long userId) {
        List<SysMenu> menuList = getMenuListByUserId(userId);
        return menuList.stream().filter(menu -> menu.getType() == 2)
                .map(SysMenu::getPerms).toList();
    }

    /**
     * 获取指定用户的菜单列表
     *
     * @param userId 用户id
     * @return 菜单列表
     */
    private List<SysMenu> getMenuListByUserId(Long userId) {
        List<SysMenu> menuList;
        //admin 超级管理员 用户id为1，拥有所有权限
        if (userId == 1) {
            LambdaQueryWrapper<SysMenu> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysMenu::getStatus, 1)
                    .orderByAsc(SysMenu::getSortValue);
            menuList = baseMapper.selectList(queryWrapper);
        } else {
            menuList = baseMapper.findListByUserId(userId);
        }
        return menuList;
    }
}




